package com.lh.lepay.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lh.lepay.common.LoginUser;
import com.lh.lepay.dao.SysUserDao;
import com.lh.lepay.entity.SysUser;
import com.lh.lepay.service.SysUserService;
import com.lh.lepay.utils.ResponseData;
import com.lh.lepay.utils.TokenUtil;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Objects;

@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserDao, SysUser> implements  UserDetailsService,SysUserService {

    @Resource
    private SysUserDao sysUserDao;


    @Resource
    private AuthenticationManager authenticationManager;

    @Resource
    private RedisTemplate redisTemplate;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 查询数据库
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getUsername, username);
        SysUser user = sysUserDao.selectOne(queryWrapper);
        if(Objects.isNull(user)){
            throw new RuntimeException("用户不存在");
        }

        // 查询权限
        List<String> list = sysUserDao.getAuthorizedListByUserId(user.getId());

        return new LoginUser(user,list);
    }

    @Override
    public ResponseData UserLoginByUsernameAndPassword(SysUser sysUser) {
        // 认证 ——》loadUserByUsername
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(sysUser.getUsername(),sysUser.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        if (Objects.isNull(authenticate)){
            throw new RuntimeException("登陆失败");
        }

        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userid = loginUser.getSysUser().getId();
        String jwt = TokenUtil.genAccessToken(userid);
        redisTemplate.opsForValue().set("login:" + userid, loginUser);

        HashMap<String, String> map = new HashMap<>();
        map.put("token", jwt);
        //redisTemplate.opsForValue().set("login:" + userid, map, 30, TimeUnit.MINUTES);
        return new ResponseData(200, "登陆成功", map);
    }

    /**
     * 注销登录
     * @return
     */
    @Override
    public ResponseData logout() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        System.out.println(authentication);
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        redisTemplate.delete("login:"+ loginUser.getSysUser().getId());

        return new ResponseData(HttpStatus.OK.value(), "注销成功");
    }
}
